<?php

namespace app\index\controller;

use app\admin\model\Client;
use app\admin\model\Course;
use app\admin\model\Sign;
use app\common\controller\Frontend;
use think\Config;
use think\Db;

class Screen extends Frontend
{

    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $layout = '';

    /**
     * @var Client
     */
    protected $clientModel = null;

    /**
     * @var Course
     */
    protected $courseModel = null;

    /**
     * @var Sign
     */
    protected $signModel = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->clientModel = new Client();
        $this->courseModel = new Course();
        $this->signModel = new Sign();
    }

    public function index()
    {
        // 各站点人数统计
        $personCountArr = $this->getPersonCountArr();
        $personNumJson = array_column($personCountArr, 'num');
        $personSiteNameJson = array_column($personCountArr, 'name');
        $this->view->assign('person_num_json', json_encode($personNumJson));
        $this->view->assign('person_site_name_json', json_encode($personSiteNameJson));

        // 站点年龄分布统计
        $age_group = $this->getAgeGroupNum();
        $this->view->assign('age_group_json', json_encode($age_group));

        // 课程安排
        $course_list = $this->getCourseList();
        $this->view->assign('course_list', $course_list);

        // 签到
        $sign_list = $this->getSignList();
        $this->view->assign('sign_list', $sign_list);

        //站点人数
        $client_num = $this->clientModel->count();
        $this->view->assign('client_num', $client_num);
        $this->view->assign('screen_title', Config::get('site.screen_title'));

        //
        $thirtyNumArr = $this->getThirtyNum();
        $this->view->assign('thiryNumArr', $thirtyNumArr);
        return $this->view->fetch();
    }


    function getThirtyNum(){

        $siteArr = [
            'xinghu' => 1,
            'honghudong' => 2,
            'tiangongdian' => 3,
            'donghubei' => 6,
            'donghunan' => 5,
            'wutonglu' => 7,
            'dingxianglu' => 8,
        ];

        $sql = "select site_id,count('*') as count from client group by site_id";
        $list = Db::query($sql);
        $result = [];
        foreach ($list as $item) {
            $result[$item['site_id']] = $item['count'];
        }

        $rate = 5;
        $arr = [
            'xinghu' => intval($result[$siteArr['xinghu']]/$rate),
            'honghudong' => intval($result[$siteArr['honghudong']]/$rate),
            'tiangongdian' => intval($result[$siteArr['tiangongdian']]/$rate),
            'donghubei' => intval($result[$siteArr['donghubei']]/$rate),
            'donghunan' => intval($result[$siteArr['donghunan']]/$rate),
            'wutonglu' => intval($result[$siteArr['wutonglu']]/$rate),
            'dingxianglu' => intval($result[$siteArr['dingxianglu']]/$rate),
        ];
        return $arr;
    }

    function getSignList(){
        $sql = "select client.name as user_name,sign.course_name, sign.course_date from sign left join client on sign.user_id = client.id";
        //$arr = $this->signModel->field('user_name, course_name, course_date')->select();
        $arr = Db::query($sql);
        $list = [];
        if(is_array($arr)){
            foreach ($arr as $k => $v){
                $item = [
                    'user_name' => $this->maskName($v['user_name']),
                    'course_name' => $v['course_name'],
                    'course_date' => $v['course_date'],
                ];
                array_push($list, $item);
            }
        }
        return $list;
    }

    /**
     * 课程排班列表
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    function getCourseList(){
        //$arr = $this->courseModel->field('weekday, course_name, course_date')->select();
        //
        $sql = "select course.weekday, course.course_name, course.course_date, service_site.name as site_name from course left join service_site on course.site_id = service_site.id";
        $arr = Db::query($sql);
        $list = [];
        if(is_array($arr)){
            foreach ($arr as $k => $v) {
                $site_name = str_replace('天宫殿养老服务中心', '中心',str_replace('养老服务站','',str_replace('重庆市渝北', '', $v['site_name'])));
                $item = [
                    'weekday' => $this->convertWeekday($v['weekday']),
                    'course_name' => truncateString($v['course_name'], 15).'-'.$site_name,
                    'course_date' => $v['course_date'],
                    'site_name' => $site_name
                ];
                array_push($list, $item);
            }
        }
        return $list;
    }

    function convertWeekday($number) {
        // 定义一个数组，用于存储大写周几的映射关系
        $weekdays = array(
            1 => '周一',
            2 => '周二',
            3 => '周三',
            4 => '周四',
            5 => '周五',
            6 => '周六',
            7 => '周日'
        );

        // 检查输入的数字是否在 1 到 7 的范围内
        if (array_key_exists($number, $weekdays)) {
            return $weekdays[$number];
        } else {
            // 如果输入的数字不在有效范围内，返回错误信息
            return "输入的数字不是有效的周几数字（1 - 7）";
        }
    }

    function maskName($name) {
        // 获取名字的长度
        $length = mb_strlen($name, 'UTF-8');

        // 如果名字长度小于等于 2，不做处理，直接返回原名字
        if ($length <= 2) {
            return $name;
        }

        // 获取名字的第一个字符
        $firstChar = mb_substr($name, 0, 1, 'UTF-8');
        // 获取名字的最后一个字符
        $lastChar = mb_substr($name, -1, 1, 'UTF-8');
        // 生成中间的星号，星号数量为名字长度减去 2
        $mask = str_repeat('*', $length - 2);

        // 拼接处理后的名字
        return $firstChar . $mask . $lastChar;
    }

    /**
     * 返回各站点人数及站点名称
     * @return array|mixed
     * @throws \think\db\exception\BindParamException
     * @throws \think\exception\PDOException
     */
    function getPersonCountArr()
    {
        $sql = 'select count(client.id) as num, service_site.name from client left join service_site on client.site_id = service_site.id group by client.site_id';
        $person_count_arr = $this->clientModel->query($sql);

        // 简化站点名称
        if(is_array($person_count_arr)){
            foreach ($person_count_arr as $k => $v){
                $person_count_arr[$k]['name'] = str_replace("养老服务", "", str_replace("重庆市渝北", "",$v['name']));
            }
        }
        return $person_count_arr;
    }


    // 站点年龄分布统计
    function getAgeGroupNum(){
        $sql = 'select
                    case
                        when age between 50 and 60 then \'50-60\'
                        when age between 61 and 70 then \'61-70\'
                        when age between 71 and 80 then \'71-80\'
                        when age between 81 and 90 then \'81-90\'
                    end as age_group,
                    count(*) as count
                    from client group by age_group';
        $age_group_arr = $this->clientModel->query($sql);
        $arr = [];
        if(is_array($age_group_arr)){
            $arr = array_column($age_group_arr,'count','age_group');
        }
        $real_arr = [];
        if(is_array($arr)){
            foreach ($arr as $k=>$value){
                if(empty($k)){
                    unset($arr[$k]);
                }else{
                    array_push($real_arr, ['value'=> $value, 'name'=>$k."岁"]);
                }
            }
        }
        return $real_arr;
    }
}
